package com.movieticket.service.impl;

import com.movieticket.dto.OrderDTO;
import com.movieticket.model.entity.Order;
import com.movieticket.model.entity.User;
import com.movieticket.repository.OrderRepository;
import com.movieticket.repository.UserRepository;
import com.movieticket.service.OrderService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private UserRepository userRepository;

    @Override
    @Transactional
    public OrderDTO createOrder(OrderDTO orderDTO) {
        User user = userRepository.findById(orderDTO.getUserId())
                .orElseThrow(() -> new RuntimeException("User not found with id: " + orderDTO.getUserId()));

        Order order = new Order();
        BeanUtils.copyProperties(orderDTO, order);

        // 手动设置ID以外的字段
        order.setMovieTitle(orderDTO.getMovieTitle());
        order.setCinemaName(orderDTO.getCinemaName());
        order.setShowtime(LocalDateTime.parse(orderDTO.getShowtime()));
        order.setSeats(orderDTO.getSeats());
        order.setTotalPrice(orderDTO.getTotalPrice());
        order.setPaymentMethod(orderDTO.getPaymentMethod());

        order.setUser(user);
        order.setStatus("PAID"); // 默认状态为已支付
        order.setOrderNumber(generateOrderNumber());
        order.setCreatedAt(LocalDateTime.now());
        order.setUpdatedAt(LocalDateTime.now());

        Order savedOrder = orderRepository.save(order);
        OrderDTO savedOrderDTO = new OrderDTO();
        BeanUtils.copyProperties(savedOrder, savedOrderDTO);
        savedOrderDTO.setUserId(savedOrder.getUser().getId());
        return savedOrderDTO;
    }

    private String generateOrderNumber() {
        return "ORD" + System.currentTimeMillis();
    }

    @Override
    public List<OrderDTO> getUserOrders(Long userId) {
        List<Order> orders = orderRepository.findByUserIdOrderByCreatedAtDesc(userId);
        return orders.stream().map(order -> {
            OrderDTO dto = new OrderDTO();
            BeanUtils.copyProperties(order, dto);
            if (order.getUser() != null) {
                dto.setUserId(order.getUser().getId());
            }
            return dto;
        }).collect(Collectors.toList());
    }

    @Override
    public OrderDTO getOrderByNumber(String orderNumber) {
        Optional<Order> orderOpt = orderRepository.findByOrderNumber(orderNumber);
        if (orderOpt.isPresent()) {
            Order order = orderOpt.get();
            OrderDTO dto = new OrderDTO();
            BeanUtils.copyProperties(order, dto);
            dto.setUserId(order.getUser().getId());
            return dto;
        }
        return null;
    }

    @Override
    public OrderDTO updateOrderStatus(String orderNumber, String status) {
        Optional<Order> orderOpt = orderRepository.findByOrderNumber(orderNumber);
        if (orderOpt.isPresent()) {
            Order order = orderOpt.get();
            order.setStatus(status);
            order.setUpdatedAt(LocalDateTime.now());
            Order savedOrder = orderRepository.save(order);
            OrderDTO dto = new OrderDTO();
            BeanUtils.copyProperties(savedOrder, dto);
            dto.setUserId(savedOrder.getUser().getId());
            return dto;
        }
        return null;
    }

    @Override
    public void deleteOrder(Long orderId) {
        orderRepository.deleteById(orderId);
    }

    @Override
    public Order findById(Long orderId) {
        return orderRepository.findById(orderId).orElse(null);
    }

    @Override
    public OrderDTO confirmOrder(OrderDTO orderDTO) {
        return createOrder(orderDTO);
    }

    @Override
    public List<Order> getAllOrders() {
        return orderRepository.findAll();
    }
} 